package com.myebills.ebpsfrontend.cust.controller;

import java.io.PrintWriter;
import java.io.IOException;
import java.net.*;
import com.checkfree.isolutions.persist.*;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.customer.persist.UserHomeImpl;
import com.checkfree.isolutions.utility.CFiError;
import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;
import com.ibm.logging.ILogger;
import com.ibm.logging.IRecordType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.checkfree.isolutions.security.Cipher; // the library

/**
 * This servlet simulates the ECS link to EBPS
 */
public class EbppxCusCorpValidateLoginServlet extends EbppxServlet {

    private static String hardKey="X2q3j5k6E7r8l93tm2n7H5qp";
    //private static String algo="3DES/PCBC/PKCS5";

    protected final void doRequest(
    HttpServletRequest req,
    HttpServletResponse res
    ) throws ServletException, java.io.IOException {

        ILogger trcLogger = getTraceLogger(req);
        final String fName = "doRequest";
		EbppxTransformer transform = new EbppxTransformer();

        try {
            String strUserName = EbppxUtil.nullToEmpty(req.getParameter("username"));
            String strPassword = EbppxUtil.nullToEmpty(req.getParameter("password"));
            String strAccounts="",strEmailAdd ="";
            EbppxCorpCustomer corpCust=null;

            if(EbppxCusDBUtil.authenticateCorpUser(strUserName,strPassword)){
				try{
					corpCust = new EbppxCorpCustomer();
					corpCust = corpCust.getCorpCustomer(strUserName);

					strAccounts = corpCust.getAccounts();
					strEmailAdd = corpCust.getEmailAdd();

				}catch(Exception e){
					System.out.println("Exception is..."+e);
				}

	            PersistServer.activate("Maxis");
	            PersistServer.beginTransaction();


            	if (trcLogger.isLogging())
            	    trcLogger.entry(IRecordType.TYPE_INFO, this, fName);

            	String param = strUserName + "," + strEmailAdd + "," + strAccounts;
            	System.out.println("Param is  ........"+param);
            	String currTimestamp = EbppxUtil.getCurrentTimestamp();
            	//String myKey = currTimestamp + hardKey;

            	if (trcLogger.isLogging()) {
            	    trcLogger.text(IRecordType.TYPE_INFO, this, fName,"parameter="+param);
            	    //trcLogger.text(IRecordType.TYPE_INFO, this, fName,"key="+myKey);
            	}

				com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();

				boolean ecsEncryptionOn = false;

				if (appCfg.hasProperty("EcsEncryption") == false)
					ecsEncryptionOn = false;
				else {
					String temp = appCfg.getProperty("EcsEncryption");
					if (temp.compareToIgnoreCase("Yes")==0){
					ecsEncryptionOn = true;
					}
				}

            	String encParam = new String();
            	if (ecsEncryptionOn) {
					encParam = transform.encrypt(param, currTimestamp, hardKey);
            		//encParam = Cipher.encryptFromString(algo, myKey, param, 0); //    the function to encrypt
				} else {
					encParam = param;
				}

            	if (trcLogger.isLogging())
            	    trcLogger.text(IRecordType.TYPE_INFO, this, fName,"encrypted parameter="+encParam);

            	String EBPSHttpHeader = "";
            	String EBPSHOST = "";
            	String EBPSPATH = "";

            	EBPSHttpHeader = appCfg.getProperty("ProxyAppHttpHeader");
            	EBPSHOST = appCfg.getProperty("ProxyAppHost");
            	EBPSPATH = appCfg.getProperty("ProxyAppPath");
            	System.out.println("Host : "+EBPSHOST);
            	System.out.println("Path : "+EBPSPATH);

            	try {

            	    req.setAttribute("_cache_refresh", "true");

            	    // if a session doesn't exist, sessionPrev is null
            	    final HttpSession sessionPrev = req.getSession(false);

            	    if (null != sessionPrev) {
            	        try {
            	            sessionPrev.invalidate();
            	        } catch (IllegalStateException e) {
            	            // Do nothing (session was already invalidated).
            	        }
            	    }

            	    // create a new session, if one doesn't already exist.
            	    final HttpSession session = req.getSession(true);
	            	//String url = EBPSHttpHeader+"://"+EBPSHOST+"/"+EBPSPATH+"/SubmitLogon?timestamp="+currTimestamp+"&param="+URLEncoder.encode(encParam);
	            	String url = "https://ebpsweb.maxis.net.my/cus/SubmitLogon?timestamp="+currTimestamp+"&param="+URLEncoder.encode(encParam);

            	    res.sendRedirect(res.encodeRedirectURL(url));

            	}
            	catch (Exception ex) {
            	    redirectToMappedUrl(
            	    req,
            	    res,
            	    EbppxConstants.URL_LOGON_FAILURE_PARAM,
            	    EbppxConstants.MESSAGE_0 + "=" + java.net.URLEncoder.encode(ex.getMessage()));
            	}


            	if (trcLogger.isLogging())
            	    trcLogger.exit(IRecordType.TYPE_INFO, this, fName);

            	// Close the connection to the database.
            	PersistServer.commitTransaction();

			}else{// end if authenticate
				// Authenticate failure
				System.out.println("Failed to login");
				redirectToMappedUrl(
                req,
                res,
                EbppxConstants.URL_LOGON_FAILURE_PARAM,
                EbppxConstants.MESSAGE_0 + "=" + java.net.URLEncoder.encode("Login failed"));
			}
        }catch (Exception cfie) {
				redirectToMappedUrl(
                req,
                res,
                EbppxConstants.URL_LOGON_FAILURE_PARAM,
                EbppxConstants.MESSAGE_0 + "=" + java.net.URLEncoder.encode(cfie.getMessage()));
            if (trcLogger.isLogging()) {
                trcLogger.text(IRecordType.TYPE_ERROR, this, fName,"encryption error="+cfie);
            }
            // Ensure that rollback is called even when an exception occurs.
            try {
                // Ensure that rollback is called even when an exception occurs.
                PersistServer.rollbackTransaction();
            }
            catch (CFiError cfie1) {
                trcLogger.text(IRecordType.TYPE_ERROR, this, fName,"encryption error="+cfie1);
            }
        }
        finally {
            PersistServer.deactivate();
        }

    }
}
